<template>
  <el-row>
    <el-col :span="12">
      <div class="new-production-order">
        <div class="main-header">
          <h2>新建生产工单</h2>
        </div>

        <!-- 基础信息卡片 -->
        <el-card class="info-card">
          <div class="card-title">基础信息</div>
          <el-row>
            <el-col :span="12">
              <el-form :model="basicInfo" label-width="80px">
                <el-form-item label="*工单名称">
                  <el-input v-model="basicInfo.workOrderName" disabled></el-input>
                  <el-checkbox v-model="basicInfo.useSystemNo">系统编号</el-checkbox>
                </el-form-item>
                <el-form-item label="*关联生产单号">
                  <el-input v-model="basicInfo.relatedProductionNo" placeholder="请选择生产单号"></el-input>
                </el-form-item>
                <el-form-item label="关联项目">
                  <el-input v-model="basicInfo.relatedProject" placeholder="请选择关联项目"></el-input>
                </el-form-item>
                <el-form-item label="负责人">
                  <el-input v-model="basicInfo.responsiblePerson" placeholder="请选择负责人"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                  <el-input v-model="basicInfo.remarks" type="textarea" :rows="2" placeholder="请输入备注"></el-input>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="12">
              <el-form :model="basicInfo" label-width="80px">
                <el-form-item label="*工单编号">
                  <el-input v-model="basicInfo.workOrderCode" placeholder="输入工单名称"></el-input>
                </el-form-item>
                <el-form-item label="销售订单">
                  <el-input v-model="basicInfo.salesOrder" placeholder="请选择销售单号"></el-input>
                </el-form-item>
                <el-form-item label="工单日期">
                  <el-date-picker v-model="basicInfo.workOrderDate" type="date" placeholder="请选日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="所属部门">
                  <el-input v-model="basicInfo.department" placeholder="请选择生产单号"></el-input>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-card>

        <!-- 生产物品卡片 -->
        <el-card class="info-card">
          <div class="card-title">生产物品</div>
          <el-row>
            <el-col :span="12">
              <el-form :model="productInfo" label-width="80px">
                <el-form-item label="*物品名称">
                  <el-input v-model="productInfo.itemName" placeholder="请选择生产物品"></el-input>
                </el-form-item>
                <el-form-item label="规格型号">
                  <el-input v-model="productInfo.specModel" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="物品类别">
                  <el-input v-model="productInfo.itemCategory" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="计划开始时间">
                  <el-date-picker v-model="productInfo.planStartDate" type="date" placeholder="请选日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="计划产量">
                  <el-input-number v-model="productInfo.planQuantity" :min="1" placeholder="请输入计划产量"></el-input-number>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="12">
              <el-form :model="productInfo" label-width="80px">
                <el-form-item label="物品编号">
                  <el-input v-model="productInfo.itemCode" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="单位">
                  <el-input v-model="productInfo.unit" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="物品分类">
                  <el-input v-model="productInfo.itemClassification" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="计划结束时间">
                  <el-date-picker v-model="productInfo.planEndDate" type="date" placeholder="请选日期"></el-date-picker>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-card>

        <!-- 工序流程卡片 -->
        <el-card class="info-card">
          <div class="card-title">工序流程</div>
          <div class="operation-buttons">
            <el-button type="primary" @click="addProcess">添加</el-button>
            <el-button type="danger" @click="removeProcess">移除</el-button>
          </div>
          <el-table :data="processList" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="processflowId" label="工序编码"></el-table-column>
            <el-table-column prop="processflowName" label="工序名称"></el-table-column>
            <el-table-column prop="processflowType" label="加工顺序"></el-table-column>
            <el-table-column prop="processflowDescription" label="工艺流程"></el-table-column>
            <el-table-column label="负责人">
              <template #default="scope">
                <el-select v-model="scope.row.processflowStatus" placeholder="请选择负责人">
                  <el-option label="请选择负责人" value=""></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="所属部门">
              <template #default="scope">
                <el-input v-model="scope.row.processflowStatusDescription" placeholder="请选择部门"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button size="small" type="text" @click="moveUp(scope.$index)">上移</el-button>
                <el-button size="small" type="text" @click="moveDown(scope.$index)">下移</el-button>
                <el-button size="small" type="text" @click="removeSingleProcess(scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="process-summary">
            <span>计划总量：{{processList.reduce((sum, item) => sum + (item.planQuantity || 0), 0)}}</span>
          </div>
        </el-card>

        <!-- 附件区域 -->
        <el-card class="info-card">
          <div class="card-title">附件</div>
          <div class="attachment-area">
            <div v-for="(file, index) in attachmentList" :key="index" class="uploaded-file">
              <div>文件名称：{{ file.name }}</div>
              <div>文件大小：{{ file.size }}</div>
              <div>上传日期：{{ file.uploadDate }}</div>
              <el-button size="small" @click="reuploadFile(index)">重新上传</el-button>
              <el-button size="small" type="danger" @click="removeFile(index)">删除</el-button>
            </div>
            <el-upload action="#" :auto-upload="false" :file-list="attachmentList" @change="handleFileChange"
              class="upload-box">
              <el-button type="primary">点击上传 / 拖拽至此区域</el-button>
            </el-upload>
            <div class="upload-tip" v-if="!attachmentList.length">
              请上传工艺文档PDF
            </div>
          </div>
        </el-card>

        <!-- 底部按钮 -->
        <div class="action-buttons">
          <el-button @click="cancel">关闭</el-button>
          <el-button type="primary" @click="saveOrder">确定</el-button>
        </div>
      </div>
    </el-col>
    <el-col :span="12">
      <!-- 选择生产单号 -->
      <el-card class="info-card" style="margin-top: 20px;">
        <div class="card-title">选择生产单号</div>
        <el-row class="query-row">
          <el-col :span="4">
            <el-input placeholder="请输入生产单号/主题" v-model="searchProductionNo.Id"></el-input>
          </el-col>
          <el-col :span="4">
            <el-date-picker placeholder="请选择单据日期" v-model="searchProductionNo.ProductionStartDate"></el-date-picker>
          </el-col>
          <el-col :span="4">
            <el-date-picker placeholder="请选择单据日期" v-model="searchProductionNo.ProductionEndDate"></el-date-picker>
          </el-col>
          <el-col :span="4">
            <el-input placeholder="请输入生产负责人" v-model="searchProductionNo.Name"></el-input>
          </el-col>
          <el-col :span="4">
            <div style="display: flex; gap: 10px;">
              <el-button type="primary" @click="searchProduction">查询</el-button>
              <el-button @click="resetSearchProduction">重置</el-button>
            </div>
          </el-col>
        </el-row>
        <el-table :data="productionList" style="margin-top: 20px;">
          <el-table-column type="radio" width="20"></el-table-column>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="id" label="生产单号"></el-table-column>
          <el-table-column prop="tu_Name" label="生产主题"></el-table-column>
          <el-table-column prop="tu_Time" label="单据日期"></el-table-column>
          <el-table-column prop="operator" label="负责人"></el-table-column>
          <el-table-column prop="remarks" label="所在部门"></el-table-column>
          <el-table-column prop="business_type" label="生产部门"></el-table-column>
        </el-table>
        <el-pagination :total="totalProduction" :page-size="pageSize" @current-change="handleProductionPage"
          style="margin-top: 10px;"></el-pagination>
      </el-card>

      <!-- 生产单号物品列表 -->
      <el-card class="info-card" style="margin-top: 20px;">
        <div class="card-title">生产单号SCDH005物品列表</div>
        <el-row class="query-row">
          <el-col :span="5">
            <el-input placeholder="请输入物品编码/名称" v-model="searchItemCodeName"></el-input>
          </el-col>
          <el-col :span="5">
            <el-select v-model="searchItemCategory" placeholder="请选择物品类别">
              <el-option label="全部" value=""></el-option>
              <el-option label="原材料" value="原材料"></el-option>
              <el-option label="半成品" value="半成品"></el-option>
              <el-option label="成品" value="成品"></el-option>
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="searchItemClassification" placeholder="请选择物品分类">
              <el-option label="全部" value=""></el-option>
              <el-option label="家具" value="家具"></el-option>
              <el-option label="电子产品" value="电子产品"></el-option>
              <el-option label="衣物" value="衣物"></el-option>
              <el-option label="食品" value="食品"></el-option>
              <el-option label="化妆品" value="化妆品"></el-option>
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="searchInventoryStatus" placeholder="库存状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="可用" value="可用"></el-option>
              <el-option label="缺货" value="缺货"></el-option>
              <el-option label="待检" value="待检"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <div style="display: flex; gap: 10px;">
              <el-button type="primary" @click="searchItemsList">查询</el-button>
              <el-button @click="resetItemsList">重置</el-button>
            </div>
          </el-col>
        </el-row>
        <el-table :data="itemsList" style="margin-top: 20px;">
          <el-table-column type="radio" width="20"></el-table-column>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="boMdateid" label="物品编码"></el-table-column>
          <el-table-column prop="boMname" label="物品名称"></el-table-column>
          <el-table-column prop="boMunit" label="规格型号"></el-table-column>
          <el-table-column prop="bomQuantity" label="可领数量"></el-table-column>
          <el-table-column prop="bomQuantityclaimed" label="已领数量"></el-table-column>
          <el-table-column prop="bomNumer" label="物品数量"></el-table-column>
          <el-table-column label="库存详情">
            <template #default="scope">
              <el-popover placement="right" width="100">
                <p>仓库一</p>
                <p>仓库二</p>
                <p>仓库三</p>
                <p>仓库四</p>
                <p>仓库五</p>
                <template #reference>
                  <el-button size="small" type="text">库存详情</el-button>
                </template>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination :total="totalItems" :page-size="pageSize" @current-change="handleItemsPage"
          style="margin-top: 10px;"></el-pagination>
      </el-card>

      <!-- 添加工艺路线 -->
      <el-card class="info-card" style="margin-top: 20px;">
        <div class="card-title">添加工艺路线</div>
        <el-row class="query-row">
          <el-col :span="18">
            <span>已勾选6项</span>
            <el-input placeholder="请搜索" v-model="searchProcessRoute"
              style="width: 300px; margin-left: 10px;"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button @click="Mokshow" style="width: 100px;">搜索</el-button>
          </el-col>
        </el-row>
        <el-table :data="processRouteList" style="margin-top: 20px;">
          <el-table-column type="checkbox" width="20"></el-table-column>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="routingId" label="工艺流程编号"></el-table-column>
          <el-table-column prop="routingName" label="工艺流程名称"></el-table-column>
          <el-table-column prop="routingTime" label="执行方式"></el-table-column>
        </el-table>
        <el-pagination :total="totalProcessRoute" :page-size="pageSize" @current-change="handleProcessRoutePage"
          style="margin-top: 10px;"></el-pagination>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import router from '@/router';

// 基础信息表单数据
const basicInfo = reactive({
  workOrderName: 'SCDN20250510113244702591',
  useSystemNo: true,
  relatedProductionNo: '',
  relatedProject: '',
  responsiblePerson: '',
  remarks: '',
  workOrderCode: '',
  salesOrder: '',
  workOrderDate: '',
  department: ''
});

// 生产物品表单数据
const productInfo = reactive({
  itemName: '',
  specModel: '',
  itemCategory: '',
  planStartDate: '',
  planQuantity: 0,
  itemCode: '',
  unit: '',
  itemClassification: '',
  planEndDate: ''
});

// 工艺流程数据
const processList = ref([]);

// 附件列表
const attachmentList = ref([
  {
    name: '新建文本文档PDF',
    size: '0 Bytes',
    uploadDate: '2022-06-01 17:45:27'
  }
]);

// 基础操作
const addProcess = () => {
  ElMessage.info('添加功能待实现');
};

const removeProcess = () => {
  ElMessage.info('批量移除功能待实现');
};

const removeSingleProcess = (index) => {
  processList.value.splice(index, 1);
  ElMessage.success('移除成功');
};

const moveUp = (index) => {
  if (index > 0) {
    [processList.value[index], processList.value[index - 1]] = [processList.value[index - 1], processList.value[index]];
  }
};

const moveDown = (index) => {
  if (index < processList.value.length - 1) {
    [processList.value[index], processList.value[index + 1]] = [processList.value[index + 1], processList.value[index]];
  }
};

const saveOrder = () => {
  const froms = {
    // "productionworkorderNameId": "",//工单名称
    // "productionworkorderId": "",//工单编号
    // "productionworkorderHId": "",//关联生产单号
    // "productionworkorderName": "",//销售订单
    // "productionworkorderType": "",//关联项目
    // "productionworkorderDescription": "",//工单日期
    // "productionworkorderStatus": "",//负责人
    // "productionworkorderDate": "",//所属部门
    // "productionworkorderWith": "",//备注
    // "productionworkorderTitle": "",//物品名称
    // "productionworkorderWId": "",//物品编码
    // "productionworkorderTypeName": "",//规格型号
    // "productionworkorderHand": "",//单位
    // "productionworkorderGender": "",//物品类别
    // "productionworkorderDorker": "",//物品分类
    // "productionworkorderNDorker": "",//计划开始时间
    // "productionworkorderJDorker": "",//计划结束时间
    // "productionworkorderNumber": "",//计划产量
    // "productionworkorderDId": "",//工序流程id
    // "productionworkorderfUJIAN": "",//附件

    "productionworkorderNameId": "", // 无对应字段，保持空
    "productionworkorderId": basicInfo.workOrderCode, // 工单编号
    "productionworkorderHId": basicInfo.relatedProductionNo, // 关联生产单号
    "productionworkorderName": basicInfo.salesOrder, // 销售订单
    "productionworkorderType": basicInfo.relatedProject, // 关联项目
    "productionworkorderDescription": basicInfo.remarks, // 备注
    "productionworkorderStatus": basicInfo.responsiblePerson, // 负责人
    "productionworkorderDate": basicInfo.workOrderDate ? basicInfo.workOrderDate.toISOString().split('T')[0] : "", // 工单日期（处理为YYYY-MM-DD格式）
    "productionworkorderWith": basicInfo.department, // 所属部门
    "productionworkorderTitle": productInfo.itemName, // 物品名称
    "productionworkorderWId": productInfo.itemCode, // 物品编码
    "productionworkorderTypeName": productInfo.specModel, // 规格型号
    "productionworkorderHand": productInfo.unit, // 单位
    "productionworkorderGender": productInfo.itemCategory, // 物品类别
    "productionworkorderDorker": productInfo.itemClassification, // 物品分类
    "productionworkorderNDorker": productInfo.planStartDate ? productInfo.planStartDate.toISOString().split('T')[0] : "", // 计划开始时间
    "productionworkorderJDorker": productInfo.planEndDate ? productInfo.planEndDate.toISOString().split('T')[0] : "", // 计划结束时间
    "productionworkorderNumber": productInfo.planQuantity.toString(), // 计划产量（转为字符串）
    "productionworkorderDId": "", // 工序流程ID（表单未提供单个流程ID，保持空）
    "productionworkorderfUJIAN": attachmentList.value.length > 0 ? attachmentList.value[0].name : "", // 附件（取第一个文件名，无则空）

  }
  console.log(froms)
  axios.post("https://localhost:7207/api/Production/Productionworkorde", froms).then((res => {
    if (res.data.code == 212) {
      ElMessage.success('保存成功');
      router.push("/NewproductionworkorderShowView")
    }
    else {
      ElMessage.info('保存失败');
    }
  }))

};

const cancel = () => {
  ElMessage.info('操作已取消');
};

// 选择生产单号相关
const searchProductionNo = reactive({
  PageIdex: 1,
  PageSize: 15,
  Batch_number: '',
  Id: '',
  Material_code: '',
  Name: '',
  Production_line: '',
  Status: '',
  Business_status: '',
  ProductionStartDate: '',
  ProductionEndDate: '',
});
const searchDate = ref('');
const searchResponsible = ref('');
const productionList = ref([])
const totalProduction = ref(36);
const pageSize = ref(5);

const searchProduction = () => {
  // 模拟搜索逻辑...
};

const resetSearchProduction = () => {
  searchProductionNo.value = '';
  searchDate.value = '';
  searchResponsible.value = '';
};

// 生产单号物品列表相关
const searchItemCodeName = ref('');
const searchItemCategory = ref('');
const searchItemClassification = ref('');
const searchInventoryStatus = ref('');
const itemsList = ref([]);
const ShowBook = () => {
  axios.get("https://localhost:7006/api/Production/ProductionShow", {
    params: {
      PageIdex: searchProductionNo.PageIdex,
      PageSize: searchProductionNo.PageSize,
      Batch_number: searchProductionNo.Batch_number,
      Id: searchProductionNo.Id,
      Material_code: searchProductionNo.Material_code,
      Name: searchProductionNo.Name,
      Production_line: searchProductionNo.Production_line,
      Status: searchProductionNo.Status,
      Business_status: searchProductionNo.Business_status,
      ProductionStartDate: searchProductionNo.ProductionStartDate,
      ProductionEndDate: searchProductionNo.ProductionEndDate,
    }
  }).then((res => {
    productionList.value = res.data.data.list
  }))
}
const totalItems = ref(36);

const searchItemsList = () => {
  // 模拟搜索逻辑...
};

const resetItemsList = () => {
  searchItemCodeName.value = '';
  searchItemCategory.value = '';
  searchItemClassification.value = '';
  searchInventoryStatus.value = '';
};

// 添加工艺路线相关
const searchProcessRoute = ref('');
const processRouteList = ref([]);
const totalProcessRoute = ref(36);

const ShowFow = () => {
  axios.get("https://localhost:7006/api/Production/BOMdetailsShow").then((res => {
    itemsList.value = res.data.data
  }))
}
const FromShow = reactive({
  PageIndex: 1,
  PageSize: 15,
  RoutingId: '',
  RoutingName: '',
})
const Mokshow = () => {
  axios.get("https://localhost:7006/api/Production/RoutingShow", {
    params: {
      PageIndex: FromShow.PageIndex,
      PageSize: FromShow.PageSize,
      RoutingId: FromShow.RoutingId,
      RoutingName: FromShow.RoutingName,
    }
  }).then((res => {
    processRouteList.value = res.data.data.list
  }))
}

const Foofok = () => {
  axios.get("https://localhost:7006/api/Process/ProductionworkorderQuser").then((res => {
    processList.value = res.data.data
  }))
}
onMounted(() => {
  ShowBook()
  ShowFow()
  Mokshow()
  Foofok()
})
</script>

<style scoped>
.new-production-order {
  padding: 20px;
  background-color: #f5f7fa;
}

.main-header h2 {
  font-weight: 500;
  color: #303133;
  margin-bottom: 20px;
}

.info-card {
  margin-bottom: 20px;
  border-radius: 4px;
  background: white;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
  padding: 0 0 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.el-row {
  margin: 0 -10px;
}

.el-col {
  padding: 0 10px;
}

.el-form-item {
  margin-bottom: 18px;
}

.operation-buttons {
  margin: 0 0 15px 0;
  display: flex;
  gap: 10px;
}

.process-summary {
  text-align: right;
  margin: 10px 0;
  color: #606266;
}

.uploaded-file {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.upload-box {
  display: inline-block;
  margin-top: 10px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}

.info-card {
  margin-bottom: 20px;
  border-radius: 4px;
  background: white;
  padding: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.el-row {
  margin: 0 -10px;
}

.el-col {
  padding: 0 10px;
}

.el-table {
  width: 100%;
  margin-top: 15px !important;
}

.el-pagination {
  margin-top: 10px;
  justify-content: center;
}

/* 查询条件区域样式 */
.query-row {
  margin: 0 -5px;
  padding: 10px 0;
}

.query-row .el-col {
  padding: 0 5px;
}

.query-row .el-input,
.query-row .el-date-picker,
.query-row .el-select {
  width: 100%;
}

.query-row .el-button {
  min-width: 80px;
}
</style>